package com.sunelec.controller;

import com.alibaba.fastjson.JSONObject;
import com.sunelec.pojo.ConfigForm;
import com.sunelec.service.ClientService;
import com.sunelec.service.Imp.ClientServiceImp;
import com.sunelec.utils.IDUtils;
import com.sunelec.utils.JSONUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: 郑明利
 * @Description: 客户端调用Controller
 * @Date: Create in 21:08 2018/04/03
 * @Modified By:
 */
@Controller
public class ClientController {

    @Autowired
    private ClientService clientService;

    @RequestMapping(value="/GetFrame",method = { RequestMethod.POST })
    @ResponseBody
    public void getFarme(HttpServletRequest request)throws Exception{
        System.out.println("123");
        JSONObject jsonObject = JSONUtils.receivePost(request);
        String FrameType = jsonObject.getString("frametype");
        System.out.println(FrameType);
        /**
         * FrameType = 0 :连接帧
         * FrameType = 1 :信息帧
         * FrameType = 2 :数据帧
         * FrameType = 3 :故障帧
         * FrameType = 4 :召唤帧
         * FrameType = 5 :透传帧
         * FrameType = 6 :设置帧
         * FrameType = 7 :心跳帧
         * FrameType = 8 :事件帧
         */
        if(FrameType.equals("2")){
            //拿出数据帧中的所有信息，写入数据库
            //json to pojo
            System.out.println(jsonObject.toString());
            ConfigForm configForm =JSONUtils.jsonToPojo(jsonObject.toString(),ConfigForm.class);
            //创建一个不重复的随机主键
            configForm.setInverter_id("Inverter_"+ IDUtils.getId());
            configForm.setUpdate_date(new Date());
            configForm.setUpdate_time(new Date());
            //将数据写入数据库
            clientService.insert(configForm);
            //将all写入日志文件
            Calendar cal = Calendar.getInstance();
            String content = "["+ new Date() + "]  " + configForm.getAll();
            String realURL = request.getServletContext().getRealPath("");
            System.out.println(realURL);
            String filePath =realURL + "/web/static/DataFram_Log/"+ cal.get(Calendar.YEAR) + "/" + cal.get(Calendar.MONTH)+1 + "/" + cal.get(Calendar.DATE)+ ".txt";
            if (writeTxtFile(content, filePath)){
                System.out.println("保存成功");
            }
        }else if(FrameType.equals("3")){
            //拿出故障帧中的所有信息，写入数据库
            //json to pojo
            //ConfigForm configForm =JSONUtils.jsonToPojo(jsonObject.toString(),ConfigForm.class);
            System.out.println(jsonObject.toString());
        }
    }

    @RequestMapping("/test")
    @ResponseBody
    public void test3(HttpServletRequest request)throws Exception{
        String json = "{\"vpv2\":\"0.0\",\"vpv1\":\"201.70000000000002\",\"dst\":\"0201\",\"tfv\":\"0.0\",\"fac\":\"0.0\",\"etoday\":\"0.0\",\"error\":\"512.0\",\"dal\":\"202240\",\"etotal\":\"0.0\",\"gvfv\":\"0.0\",\"powerontime\":\"655\",\"mode\":\"2.0\",\"ipv2\":\"10.100000000000001\",\"htotal\":\"0.0\",\"ipv1\":\"0.0\",\"lact\":\"6553.5\",\"offsettime\":\"1518146489\",\"lacr\":\"0.0\",\"frametype\":\"2\",\"lacs\":\"6553.5\",\"datatype\":\"1\",\"serverserialnum\":\"3\",\"gffv\":\"0.0\",\"all\":\"A587001042D302813B607101020181DC03008F020000B9137D5A0100001603000045494E3230323031313630303138369600E1070000000065000000FFFFFFFF0000FFFFFFFF0000FEFF010000000000000000000000000002000002000000000000FFFF0000000000004531312D56392E322D393834300000000000000056372E312D373136383900000000000000000000EC15\",\"ptotal\":\"131070.0\",\"temp\":\"15.0\",\"pvfv\":\"0.0\",\"devicesn\":\"1902132097\",\"clientserialnum\":\"2\",\"dver1\":\"E11-V9.2-9840\",\"vact\":\"6553.5\",\"dver2\":\"V7.1-71689\",\"vacs\":\"6553.5\",\"vacr\":\"0.0\",\"ra\":\"1\",\"gzfv\":\"65.535\",\"pd\":\"253057\",\"gfci\":\"0.0\",\"datalength\":\"135\",\"dsn\":\"EIN202011600186\"}";

        ConfigForm configForm =JSONUtils.jsonToPojo(json ,ConfigForm.class);
        //将数据写入数据库
        configForm.setInverter_id("zmlTest123");
        configForm.setDailyelec(15);
        configForm.setUpdate_date(new Date());
        configForm.setUpdate_time(new Date());
        clientService.insert(configForm);
    }

    /**
     * 向TXT中写入内容，不存在就创建txt格式的log文件
     */
    public static boolean writeTxtFile(String content, String filePath){
        boolean flag = false;
        File newF = new File(filePath);
        try{
            if(!newF.exists()){
                newF.createNewFile();
            }
            BufferedWriter bw = new BufferedWriter(new FileWriter(filePath));
            bw.write(content);
            bw.write("\r\n");
            bw.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        flag = true;
        return flag;
    }
}
